#!/bin/bash

# 生成自签名CA证书和私钥,有效期100年
openssl req -x509 -newkey rsa:4096 -keyout ca.key -out ca.crt -days 36500 -nodes -subj "/C=CN/ST=Beijing/L=Beijing/O=Harbor/OU=Harbor/CN=MyPrivateCA"

# 生成证书和私钥的文件名
certfile="harbor.crt"
keyfile="harbor.key"

# 设置主题和SAN (Subject Alternative Names)
common_name="harbor.example.com"
#san_list="DNS:harbor.example.com,IP:192.168.1.100,IP:10.0.0.100"
san_list="DNS:harbor.example.com"

# 生成证书配置文件
cat <<EOF > openssl.cnf
[req]
distinguished_name = req_distinguished_name
req_extensions = v3_req

[req_distinguished_name]
CN = $common_name

[v3_req]
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth
subjectAltName = $san_list
EOF

# 生成证书签发请求
openssl req -new -newkey rsa:2048 -keyout $keyfile -out csr.pem -nodes -config openssl.cnf

# 使用CA证书和私钥签发Harbor证书，有效期100年
openssl x509 -req -in csr.pem -CA ca.crt -CAkey ca.key -CAcreateserial -out $certfile -days 36500 -extfile openssl.cnf -extensions v3_req

# 清理临时文件
rm csr.pem
rm openssl.cnf

echo "CA证书已生成：ca.crt"
echo "Harbor证书已生成：$certfile"
echo "Harbor私钥已生成：$keyfile"

# 可选：将证书和私钥移动到Harbor所需的位置
# mv ca.crt /your/harbor/directory
# mv $certfile /your/harbor/directory
# mv $keyfile /your/harbor/directory

# 查看证书有效期
# openssl x509 -in harbor.crt -noout -text